package com.yupfeg.test

import android.annotation.SuppressLint
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.lifecycle.Observer
import com.yupfeg.livedata.R
import com.yupfeg.test.app.AppShareViewModel
import com.yupfeg.test.base.applicationViewModelDelegate
import com.yupfeg.test.share.FragmentSharedActivity
import com.yupfeg.test.simple.SimpleEventActivity

class MainActivity : AppCompatActivity() {
    private val mAppShareViewModel : AppShareViewModel by applicationViewModelDelegate()

    private val mForeverObserver : Observer<String> by lazy(LazyThreadSafetyMode.NONE){
        createForeverEventObserve()
    }

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        findViewById<View>(R.id.btn_simple_use).setOnClickListener {
            startActivity(Intent(this,SimpleEventActivity::class.java))
        }

        findViewById<View>(R.id.btn_share_fragment_event).setOnClickListener {
            startActivity(Intent(this,FragmentSharedActivity::class.java))
        }

        mAppShareViewModel.foreverEvent.observeForever(mForeverObserver)
    }

    override fun onDestroy() {
        super.onDestroy()
        //注意，对于生命周期不敏感的订阅，需要在视图移除时，移除订阅者
        mAppShareViewModel.foreverEvent.removeObserver(mForeverObserver)
    }

    private fun createForeverEventObserve() : Observer<String> {
        return Observer {event->
            Log.d("logger","接收到forever event : $event")
            Toast.makeText(this,"receive foreverEvent",Toast.LENGTH_SHORT).show()
        }

    }
}